#!/bin/sh
#
# Generates cli_help.cpp from the command documentation on the Google
# Code wiki.
#
# Wiki html -> text conversion is performed by w3m, which you can get at
# http://w3m.sourceforge.net
#
# github-markdown-preview can be installed via gem
#
# Joseph Xu March 2011
# Modified  March 2012

echo "Attempting to generate Soar CLI help file. (../cli_help.cpp)"

TEXTDIR=helptext

if ! [ -x "`which html2text`" -a -x "`which github-markdown-preview`" ]
then
echo please install html2text and github-markdown-preview
exit 1
fi

echo "Downloading wiki files from repository..."

git clone https://github.com/SoarGroup/Soar.wiki.git

echo "Converting to html..."

for file in Soar.wiki/ManualsAndFAQs/CLI/cmd_*.md; do
	github-markdown-preview $file &
	PID=$!

	while [ ! -f $file.html ]
	do
		sleep 0.01
	done

	sed '/<head/,/<\/head>/d' $file.html > ${file%.md}.html
	html2text -ascii -style pretty -nobs -o ${file%.md}.txt ${file%.md}.html

	kill $PID
done

echo "/* Auto-generated by gen_cli_help.sh on `date` */" > src/cli_help.cpp
cat cli_help_head.cpp >> src/cli_help.cpp

echo "Converting to raw text..."

for f in Soar.wiki/ManualsAndFAQs/CLI/cmd_*.txt
do
	b=`basename $f`
	b2=${b%.*}
	c=${b2#cmd_}
    echo "... $c"
	awk '
		BEGIN {
			cmdname = "'$c'"
			gsub("_", "-", cmdname)
			inhead = 1
		}
		inhead == 1 {
			if (NF > 1 || (NF == 1 && $1 != cmdname)) {
				inhead = 0
				linecount = 1
			}
		}
		inhead == 0 {
			if (lines[linecount-1] ~ /^[ \t]*$/ && $0 ~ /^[ \t]*$/) {
				# skip double blanks
				next
			}
			lines[linecount++] = $0
		}
		END {
			for (i = linecount; i >= 1; i--) {
				if (lines[i] !~ /^[ \t]*$/) {
					last = i
					break
				}
			}
			print "	docstrings[\"" cmdname "\"] = "
			for (i = 1; i <= last; i++) {
				gsub("\\\\", "\\\\", lines[i])
				gsub("\"", "\\\"", lines[i])
				gsub("&#x27;", "'"'"'", lines[i])
				print "		\"" lines[i] "\\n\""
			}
			print "	;"
		}' "$f" >> src/cli_help.cpp
done

echo "}" >> src/cli_help.cpp

echo "Cleaning up..."

rm -rf Soar.wiki

echo "Successfully generated cli_help.cpp from wiki entries!"
